package com.project.api.common;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Controller
public class UnitController {
    @Value("${jar.fileUrl}")
    private String uploadFolder;

    @RequestMapping(value="/verify/uploadfile",method = RequestMethod.POST)
    @ResponseBody
    public String Upload(HttpServletRequest request, Model model, @RequestParam(value = "file") MultipartFile file, HttpSession session) {
//        String path = System.getProperty("user.dir");
        //文件上传的地址
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = new Date(System.currentTimeMillis());
            String dateStr = simpleDateFormat.format(date);
//            String  destDir=session.getServletContext().getRealPath("/static/upload/");
//            String path = destDir +dateStr;
//            String path = ResourceUtils.getURL("classpath:").getPath() + "static/upload/"+dateStr;
//            String realPath = path.replace('/', '\\').substring(1, path.length());
            String realPath=uploadFolder+dateStr;
            if (file.isEmpty()) {
                return ApiResponse.Fail("文件为空空");
            }
            File dirs=new File(realPath);
            if(!dirs.exists()){
                dirs.mkdirs();
            }
            String fileName = file.getOriginalFilename();  // 文件名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
//            String filePath = "D://temp-rainy//"; // 上传后的路径
            String filePath = realPath;
            fileName = UUID.randomUUID() + suffixName; // 新文件名
            File dest = new File(filePath +"\\"+ fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
            }
//            String filename = "/temp-rainy/" + fileName;
//            model.addAttribute("filename", filename);
            String fileRoot="/upload/"+dateStr+"/"+fileName;
            JSONObject obj=new JSONObject();
            obj.put("filepath",fileRoot);
            obj.put("location",fileRoot);
            return ApiResponse.Ok("上传成功",obj);
        }catch (Exception e) {
                e.printStackTrace();
            return ApiResponse.Fail("文件或目录不存在");
        }
    }


    @RequestMapping(value="/verify/deletefile",method = RequestMethod.POST)
    @ResponseBody
    public String Delete(HttpServletRequest request, Model model, @RequestBody JSONObject json) {
        try {
            String resultInfo = null;
            String path = (String) json.getOrDefault("file",null);
            if (path == null) return ApiResponse.Ok("请求参数失败",null);
            //System.out.println(path);///imctemp-rainy/2.jpg
//            int lastIndexOf = path.lastIndexOf("/");
//            String file_path = path.substring(lastIndexOf + 1, path.length());
            String root = ResourceUtils.getURL("classpath:").getPath() + "static"+path;
            String realPath = root.replace('/', '\\').substring(1, root.length());
//            String realPath = root.replace('/', '\\');
//            realPath = realPath;
            //System.out.println(img_path);//输出测试一下文件路径是否正确
            File file = new File(realPath);
            if (file.exists()) {//文件是否存在
                if (file.delete()) {//存在就删了，返回1
                    resultInfo =  "1";
                } else {
                    resultInfo =  "0";
                }
            } else {
                resultInfo = "文件不存在！";
            }
            return ApiResponse.Ok("删除:"+resultInfo,null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return ApiResponse.Ok("删除成功",null);
    }
}
